package com.qf.controller;
/**
 * @author ZERO
 * @date 2021/12/24 11:08
 */

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.List;

/**
 *@program: com.qf.controller
 *@description:
 *@author: ZERO
 *@create: 2021/12/24 11:08
 */
@RestController
@RequestMapping("movie-suggest")
public class MovieSuggestController {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;


    //    GET movies/_search
//    {
//        "suggest": {
//        "title-suggest": {
//            "prefix": "m",
//                "completion": {
//                "field": "title",
//                "skip_duplicates": true
//            }
//        }
//    }
//    }

    @RequestMapping("fingdSuggestMoies")
    public Object findMovies(String text){
        //设置条件
        CompletionSuggestionBuilder completionSuggestionBuilde =
        new CompletionSuggestionBuilder("title")//从指定属性中推荐
        .prefix(text)//获取前缀
        .size(13)//显示数量
        .skipDuplicates(true);//去重

        //封装条件
        SuggestBuilder suggestBuilder = new SuggestBuilder()
                .addSuggestion("title-suggest",completionSuggestionBuilde);
        //获取SearchResponse
        SearchResponse searchResponse = elasticsearchRestTemplate
                .suggest(suggestBuilder, IndexCoordinates.of("movie"));
        //获取Suggest对象
        Suggest suggest = searchResponse.getSuggest();
        //创建集合，用于存储推荐的电影对象
        HashSet<String> set = new HashSet<>();
        //获取Suggestion对象，名称要和上面addSuggestion方法中的名称一致
        Suggest.Suggestion suggestion =
                suggest.getSuggestion("title-suggest");
        List entries = suggestion.getEntries();
        if (entries.size()>0){
            Object obiect = entries.get(0);
            if (obiect instanceof CompletionSuggestion.Entry) {
                CompletionSuggestion.Entry entry = (CompletionSuggestion.Entry)obiect;
                List<CompletionSuggestion.Entry.Option> options = entry.getOptions();
                for (CompletionSuggestion.Entry.Option option : options){
                    String suggestMovie = option.getText().toString();
                    set.add(suggestMovie);
                }
            }
        }
        return set;
    }
}
